package divestoclimb.checklist.data;

import divestoclimb.checklist.storage.DbAdapter;

//A class for a checklist template. This is also a superclass for Checklist.
public class Template {

	protected long mID;				// The ID of this template in the database
	protected Category mCategory;	// The category of this template
	protected String mName;			// The name of this template
	protected String mVersion;		// The version of this template
	protected boolean mDirty;		// Whether or not this record needs to be
									// updated in the database
	
	// Getters and Setters
	public long getID() { return mID; }
	protected void setID(long id) { mID=id; }
	public Category getCategory() { return mCategory; }
	public void setCategory(Category c) { if(! c.equals(mCategory)) { mCategory=c; mDirty=true; } }
	public String getName() { return mName; }
	public void setName(String name) { if(mName != name) { mName=name; mDirty=true; } }
	public String getVersion() { return mVersion; }
	public void setVersion(String version) { if(mVersion != version) { mVersion = version; mDirty = true; } } 
	
	// Constructors
	/**
	 * This one is used to build a brand new Template. No ID is included because
	 * none exists. Only fields required in the database are passed to the
	 * constructor, the rest can be set with setters.
	 * @param name
	 */
	public Template(String name) {
		mID = -1;
		mName=name;
		mCategory=null;
		mDirty=true;
	}
	
	/**
	 * This constructor is used when loading a template from the database in
	 * DbAdapter. All fields are passed.
	 * @param id
	 * @param category
	 * @param name
	 * @param version
	 */
	public Template(long id, Category category, String name, String version) {
		mID=id;
		mCategory=category;
		mName=name;
		mVersion=version;
		// Because this is just an instance of the database record being populated,
		// nothing has actually changed so clear the Dirty bit.
		mDirty=false;
	}
	
	/**
	 * Save the template back to the database
	 * @param d The DbAdapter to use to access the database
	 * @return True if the save was successful, false if it not or if it was
	 * not necessary.
	 */
	public boolean save(DbAdapter d) {
		if(! mDirty) { return false; }
		boolean success;
		if(mID == -1) {
			mID=d.createTemplate(this);
			success = mID != -1;
		} else {
			success = d.updateTemplate(this);
		}
		mDirty = ! success;
		return success;
	}

}